<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 * 
 * 创建时间：2021-10-15 12:41
 *
 * 项目：rm  -  $  - UploadHelper.php
 *
 * 作者：liwei 
 */

namespace lev\helpers;

use Lev;
use lev\base\Imagev;
use lev\base\Uploadv;
use lev\widgets\uploads\uploadsWidget;
use modules\levs\modules\uploads\helpers\uploadsColumnsHelper;
use modules\levs\modules\uploads\helpers\uploadsInterfaceHelper;
use modules\levs\modules\uploads\table\uploads\uploadsModelHelper;
use modules\levs\modules\uploads\table\uploads_use\uploadsUseModelHelper;

!defined('INLEV') && exit('Access Denied LEV');


class UploadHelper extends Uploadv
{

    public static function thumbSrc($src, $thumbPre = '/thumb_150_0_') {
        $rootSrc = Lev::uploadRootSrc($src);
        $thumbName = $thumbPre.basename($src);
        if (is_file(dirname($rootSrc) . $thumbName)) {
            return dirname($src) . $thumbName;
        }
        return $src;
    }


    public static function ckUse($callid, $calliden, $calltype = null)
    {
        if (ModulesHelper::isInstallModule('uploads')) {
            $where = ['callid'=>$callid, 'calliden'=>$calliden];
            $calltype !== null &&
            $where['calltype'] = $calltype;
            return uploadsUseModelHelper::findOne($where);
        }
        return null;
    }

    /**
     * @param $callidArr
     * @param $calliden
     * @param $calltype
     * @param string $fileds
     * @param null $atype
     * @return array
     * @see uploadsColumnsHelper::atype()
     */
    public static function getCallImagesAll($callidArr, $calliden, $calltype, $fileds = '') {
        return static::getCallImages($callidArr, $calliden, $calltype, 0, $fileds);
    }
    public static function getCallImages($callidArr, $calliden, $calltype = '', $inorder = 3, $fileds = '') {
        return static::getCallUploads($callidArr, $calliden, $calltype, $inorder, $fileds, 1);
    }
    public static function getCallUploads($callidArr, $calliden, $calltype = null, $inorder = 3, $fileds = '', $atype = null) {
        $imgsArr = [];
        if ($callidArr && ModulesHelper::isInstallModule('uploads')) {
            $insql = is_array($callidArr) ? implode(',', $callidArr) : $callidArr;
            $inorder = intval($inorder);
            $inorderStr = $inorder >0 ? 'AND a.inorder<='.$inorder : '';
            $atype !== null &&
            $inorderStr .= ' AND b.atype='.$atype;
            $calltype !== null &&
            $inorderStr .= " AND a.calltype='{$calltype}'";
            $fileds .= ($fileds ? ',' : '').' a.callid, a.awidth, a.aheight, a.inorder, a.uid, b.src, b.uid as authorid ';
            $sql = "SELECT $fileds FROM ".uploadsUseModelHelper::tableName().' a LEFT JOIN '.uploadsModelHelper::tableName()." b ON a.uploadsid=b.id WHERE a.callid IN($insql) $inorderStr AND a.calliden='{$calliden}'";
            $imgs = uploadsUseModelHelper::findAll($sql);
            if (is_numeric($callidArr)) {
                $imgsArr = $imgs;
            }else {
                foreach ($imgs as $v) {
                    $imgsArr[$v['callid']][] = $v;
                }
            }
        }
        return $imgsArr;
    }

    public static function saveUses($uploadsids, $calltype, $callid, $calliden, $uid = 0) {
        if (ModulesHelper::isInstallModule('uploads')) {
            uploadsInterfaceHelper::saveUses($uploadsids, $calltype, $callid, $calliden, $uid);
        }
    }
    public static function saveUse($uploadsid, $calltype, $callid, $calliden, $uid = 0) {
        if (ModulesHelper::isInstallModule('uploads')) {
            uploadsInterfaceHelper::saveUse($uploadsid, $calltype, $callid, $calliden, $uid);
        }
    }

    /**
     * Array
    (
    [0] => 290
    [1] => 69
    [2] => 3
    [3] => width="290" height="69"
    [bits] => 8
    [mime] => image/png
    )
     * @param $src
     * @param $rootSrc
     * @param null $webroot
     * @param null $iden
     * @param null $atype
     * @param string $input
     * @param string $dirtype
     * @param string $aname
     * @param array $data
     * @return array|null
     */
    public static function saveAttachmentInfoImage($src, $rootSrc, $descs = '', $webroot = null, $iden = null, $input = '', $dirtype = '', array $data = []) {
        if (!ModulesHelper::isInstallModule('uploads')) {
            return null;
        }
        if (($rootSrc && is_file($rootSrc)) || is_file($rootSrc = Lev::uploadRootSrc($src, $webroot))) {
            if (!$src) {
                $_webroot = $webroot === null ? rtrim(Lev::dataUpload(), '/') : $webroot;
                $src = substr($rootSrc, strlen(Lev::$aliases['@webroot'] . $_webroot));
            }
            $imginfo = getimagesize($rootSrc);
            $amime = $imginfo['mime'];
            $asuffix = explode('/', $amime)[1];
            $awidth = $imginfo[0];
            $aheight = $imginfo[1];
            $asize = filesize($rootSrc);
            $aname = basename($src);
            $data['descs'] = $descs;
            $atype = 1;
            return static::saveAttachmentInfo($src, $asuffix, $amime, $awidth, $aheight, $asize, $webroot, $iden, $atype, $input, $dirtype, $aname, $data);
        }
        return Lev::responseMsg(-1, '文件不存在：'.$rootSrc);
    }
    public static function saveAttachmentInfo($src, $asuffix, $amime, $awidth, $aheight, $asize, $webroot = null, $iden = null, $atype = null, $input = '', $dirtype = '', $aname = '', array $data = []) {
        if (ModulesHelper::isInstallModule('uploads')) {
            return uploadsInterfaceHelper::saveAttachmentInfo($src, $asuffix, $amime, $awidth, $aheight, $asize, $webroot, $iden, $input, $dirtype, $aname, $atype, $data);
        }
        return null;
    }

    /**
     * @param $files
     * @param string $dir
     * @param int $isimg
     * @param array $ext
     * @param int $uploadsize KB
     * @param int $cutWidth
     * @param string $fileroot
     * @param string $dirtype
     * @return array|bool
     * @see uploadsInterfaceHelper::saveAttachmentUploads()
     */
    public static function upload($files, $dir = '', $isimg = 1, $ext = [], $uploadsize = 0, $cutWidth = 150, $fileroot = '', $dirtype = 'album', $returnRootSrc = false) {
        if (($msg = static::checkUploadError($files, $isimg, $uploadsize))) {
            return $msg;
        }
        if (empty($files) || !is_array($files)) {
            return Lev::responseMsg(-100, '请上传文件');
        }
        if (!$isimg) {
            $ext = $ext ? $ext : static::exts();
        }

        $_fileroot = $fileroot;
        $dir = '/'.Lev::$app['iden'].($dir ? '/'.$dir.'/' : '/');
        !$fileroot && $fileroot = Lev::getAlias('@uploads');
        $fileroot .= $dir;
        cacheFileHelpers::mkdirv($fileroot);
        Uploadv::$uploadDir = $fileroot;
        $upload = new Uploadv();

        $dirtype = $upload->check_dir_type($dirtype);

        if($upload->init($files, $dirtype) && $upload->save(1)) {//print_r($upload->attach);
            if ($isimg && !$upload->attach['isimage']) {
                @chmod($upload->attach['target'], 0644);
                @unlink($upload->attach['target']);
                return Lev::responseMsg(-1105, '请上传一张图片');
            }elseif (!empty($ext) && !in_array(ltrim($upload->attach['ext'], '.'), $ext)) {
                @chmod($upload->attach['target'], 0644);
                @unlink($upload->attach['target']);
                return Lev::responseMsg(-1106, '上传文件必须是：'.implode(', ', $ext));
            }else{
                if (!$isimg && !in_array($upload->attach['ext'], array('zip', 'rar'))) {
                    rename($upload->attach['target'], $upload->attach['target'].= '.'.$upload->attach['ext']);
                    $upload->attach['attachment'] .= '.'.$upload->attach['ext'];
                }
                $upload = uploadsWidget::formatAttachName($upload);
                $src = $dir.$dirtype.'/'.$upload->attach['attachment'];
                $svdataid = 0;
                if (ModulesHelper::isInstallModule('uploads')) {
                    $spm = [$src, $upload, $_fileroot];
                    $svdata = Lev::actionObjectMethod('modules\levs\modules\uploads\helpers\uploadsInterfaceHelper', $spm, 'saveAttachmentUploads');
                    $svdataid = $svdata['id'];
                    if ($isimg && $svdata && $svdata['atype'] != 1) {
                        return Lev::responseMsg(-11051, '请正确上传图片，此图片无法读取');
                    }
                }
                if ($upload->attach['isimage'] && $files['size'] >1024000) {//超过1M图片自动裁剪成缩略图
                    ini_set('memory_limit', '-1'); //图片的裁剪非常占内存
                    $src = static::cutImage($src, $cutWidth, 0);
                }
                $realSrc = Lev::uploadRealSrc($src);
                return Lev::responseMsg(1, '上传成功', [
                    'src'=>$src, 'realSrc'=>$realSrc, 'rootSrc'=> $fileroot || $returnRootSrc ? $upload->attach['target'] : '',
                    'uploaded' => 1, 'url' => $realSrc, 'fileName' => basename($realSrc),
                    'dbId' => $svdataid,
                ]);
            }
        }
        return Lev::responseMsg(-1108, '保存失败', [$upload->errormessage(), $upload->attach]);
    }

    public static function cutImage($src, $width = 100, $height = 100, $type = 1) {
        $sourcesrc = str_replace(Lev::$aliases['@siteurl'], '', Lev::uploadRootSrc($src));
        $imagename = basename($sourcesrc);
        $path = '/thumb_'.$width.'_'.$height.'_'.$imagename;
        $fileroot  = dirname($sourcesrc);
        $rootsrc = $fileroot.$path;
        if (is_file($rootsrc)) {
            return dirname($src) . $path;
        }elseif ($type ==99) {
            return $src;
        }elseif (!in_array($type, array(1, 2))) {
            return $src;
        }

        $image = new Imagev();
        $image::$fileroot = rtrim($fileroot, '/').'/';
        $type = in_array($type, array(1, 2)) ? $type : 2;
        if($image->Thumb($sourcesrc, $path, $width, $height, $type)) {
            return dirname($src) . $path;
        }else {
            return $src;
        }
    }

    public static function checkUploadError($thumb, $isimage = 1, $uploadsize = 0) {
        if ($thumb['error']) {
            return Lev::responseMsg(-110, '文件上传失败！'.$thumb['error']);
        }elseif ($uploadsize && $thumb['size'] > $uploadsize * 1024) {
            $uploadsizestr = $uploadsize > 1024 ? round($uploadsize/1024, 2).'M' : $uploadsize.'KB';
            return Lev::responseMsg(-1101, '操作失败！上传文件超出限制【'.$uploadsizestr.'】');
        }elseif ($isimage && stripos($thumb['type'], 'image') === false) {
            return Lev::responseMsg(-1102, '操作失败！请上传图片文件！');
        }
        return false;
    }

    private static function exts()
    {
        return [];//['jpg', 'gif']
    }
}